﻿using System;
using System.Net;
using NWMES.Mes;
using NWMES.MachineIntegrationServiceService;
using Newtonsoft.Json;
using NWMES;
using System.Collections.Generic;
using System.Linq;
using BaseUtils.Helper;
using NWMES.Model;

namespace MyMes.Mes
{

    /// <summary>
    /// 收数 出战 （总成完成）
    /// </summary>
    public class MachineIntegration : MESBaseService
    {
        static string DefaultApiSection = "MachineIntegration";
        public static NetworkCredential networkCredential = null;
        public static MachineIntegration Params = null;

        static MachineIntegration()
        {
            Params = config[DefaultApiSection].ToObject<MachineIntegration>();
            networkCredential = new NetworkCredential(Params.UserName, Params.Password);
        }

        /// <summary>
        /// MES收数
        /// 常用来带数据出站
        /// </summary>
        /// <param name="sfc"></param>
        /// <param name="MesData"></param>
        /// <param name="ApiSection"></param>
        /// <returns></returns>
        public static MesResult RequestMes(
            string sfc, List<MachineIntegrationParamData> MesData,
            string ApiSection)
        {
            if (!string.IsNullOrEmpty(ApiSection))
            {
                Params = config[ApiSection].ToObject<MachineIntegration>();
                networkCredential = new NetworkCredential(Params.UserName, Params.Password);
            }
            else
            {
                ApiSection = DefaultApiSection;
            }
            string ErrorMessage = Params.ParameterVerification();
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                MesResult d =  new MesResult(-99, ErrorMessage);
                MesResult sd = new MesResult();
                sd.Success = true;
                sd.Code = 2;
                d.Respone = sd;
                d.ResponeJson = JsonConvert.SerializeObject(sd);
                //object d =ConvertHelper.ToObject<object>(d.ResponeJson);
                return d;
            }
            MachineIntegrationServiceService machineIntegrationServiceService;
            dcForModuleTestRequest Request;

            SetRequestParams(out machineIntegrationServiceService, out Request);

            Request.sfc = sfc;

            if (MesData?.Count > 0)
            {
                Request.parametricDataArray = MesData.Select(a =>
                {
                    machineIntegrationParametricData param = new machineIntegrationParametricData() { name = a.Name, value = a.Value, dataType = a.DataType.ToString().ToEnum<ParameterDataType>() };
                    return param;
                }).ToArray();
            }

            dataCollectForModuleTestResponse Response = new dataCollectForModuleTestResponse();

            MesResult result = MesResult.InitMesResult(JsonConvert.SerializeObject(Request));
            dataCollectForModuleTest DataCollectForSfc = new dataCollectForModuleTest();
            DataCollectForSfc.DcForModuleTestRequest = Request;

            try
            {
                Response = machineIntegrationServiceService.dataCollectForModuleTest(DataCollectForSfc);
                result.EndTime = DateTime.Now;
                var ret = Response.@return;
                result.Message = ret?.message;
                result.Code = ret.code;
                result.Success = result.Code == 0;
                result.ResponeJson = JsonConvert.SerializeObject(Response);

                result.Respone = Response;
                result.ret = ret;
            }
            catch (Exception ex)
            {
                result.Code = -99;
                result.Message = ex.Message;
            }

            SaveMesLog(ApiSection, result);
            return result;
        }

        /// <summary>
        /// MES不带数据出站
        /// </summary>
        /// <param name="sfc"></param>
        /// <param name="MesData"></param>
        /// <param name="ApiSection"></param>
        /// <returns></returns>
        public static MesResult SfcComplateMes(string sfc, string ApiSection)
        {
            if (!string.IsNullOrEmpty(ApiSection))
            {
                Params = config[ApiSection].ToObject<MachineIntegration>();
                networkCredential = new NetworkCredential(Params.UserName, Params.Password);
            }
            else
            {
                ApiSection = DefaultApiSection;
            }

            MachineIntegrationServiceService machineIntegrationServiceService;
            sfcComplete Request;

            SetSfcComplateRequestParams(out machineIntegrationServiceService, out Request);
            Request.CompleteSfcRequest.sfcArray = new string[] { sfc };

            sfcCompleteResponse Response = new sfcCompleteResponse();
            MesResult result = MesResult.InitMesResult(JsonConvert.SerializeObject(Request));

            try
            {
                Response = machineIntegrationServiceService.sfcComplete(Request);
                result.EndTime = DateTime.Now;
                var ret = Response.@return;
                result.Message = ret?.message;
                result.Code = ret.code;
                result.Success = result.Code == 0;
                result.ResponeJson = JsonConvert.SerializeObject(Response);
            }
            catch (Exception ex)
            {
                result.Code = -99;
                result.Message = ex.Message;
            }

            SaveMesLog(ApiSection, result);
            return result;
        }

        private static void SetRequestParams(
            out MachineIntegrationServiceService machineIntegrationServiceService,
            out dcForModuleTestRequest DcForModuleTestRequest)
        {
            machineIntegrationServiceService = new MachineIntegrationServiceService();
            machineIntegrationServiceService.Url = Params.Url;
            machineIntegrationServiceService.Timeout = Params.Timeout;
            machineIntegrationServiceService.Credentials = networkCredential;
            machineIntegrationServiceService.PreAuthenticate = true;
            DcForModuleTestRequest = new dcForModuleTestRequest();
            DcForModuleTestRequest.site = Params.Site;
            DcForModuleTestRequest.user = Params.User;
            DcForModuleTestRequest.operation = Params.Operation;
            DcForModuleTestRequest.operationRevision = Params.OperationRevision;
            DcForModuleTestRequest.activityId = Params.ActivityId;
            DcForModuleTestRequest.resource = Params.Resource;

            DcForModuleTestRequest.dcGroup = Params.DcGroup;
            DcForModuleTestRequest.dcGroupRevision = Params.DcGroupRevision;
            DcForModuleTestRequest.modeProcessSfc = ConvertHelper.ToEnum<dataCollectForSfcModeProcessSfc>(Params.ModeProcessSFC);
        }

        private static void SetSfcComplateRequestParams(
    out MachineIntegrationServiceService machineIntegrationServiceService,
    out sfcComplete _sfcComplete)
        {

            sfcComplete req = new sfcComplete();
            req.CompleteSfcRequest = new completeSfcRequest();

            machineIntegrationServiceService = new MachineIntegrationServiceService();
            machineIntegrationServiceService.Url = Params.Url;
            machineIntegrationServiceService.Timeout = Params.Timeout;
            machineIntegrationServiceService.Credentials = networkCredential;
            machineIntegrationServiceService.PreAuthenticate = true;
            req.CompleteSfcRequest.site = Params.Site;
            req.CompleteSfcRequest.user = Params.User;
            req.CompleteSfcRequest.operation = Params.Operation;
            req.CompleteSfcRequest.operationRevision = Params.OperationRevision;
            req.CompleteSfcRequest.resource = Params.Resource;

            _sfcComplete = req;
        }
        public void ReloadConfig()
        {
            RefreshConfig();
            Params = config["MachineIntegration"].ToObject<MachineIntegration>();
        }

        /// <summary>
        /// DC参数数组参数名称
        /// </summary>
        public string name { get; private set; } = "";

        /// <summary>
        /// NC参数数组NCCODE
        /// </summary>
        public string ncCode { get; private set; } = "";

        /// <summary>
        /// NC参数数组布尔值
        /// </summary>
        public string hasNc { get; private set; } = "";
    }
}
